<!-- 用例上传模块，支持XMind和Excel -->
<template>
  <el-dialog title="上传用例" :visible.sync="visible" width="50%">
    <!-- 这里面的data可以用来传递额外参数，uploadParams = {'key':'value', 'key':'value'} -->
    <el-upload
      class="upload-demo"
      action="no-use"
      name="file"
      :http-request="myUpload"
      :data="uploadParams"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-remove="beforeRemove"
      multiple
      :limit="3000"
      :on-exceed="handleExceed"
      :on-success="resourceUploadSuccess"
      :on-error="resourceUploadError"
      :file-list="fileList"
    >
      <el-button size="small" type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">可以在这里上传脚本和相关的资源文件，如：excel、csv等</div>
    </el-upload>
  </el-dialog>
</template>

<script>
import axios from 'axios'
import store from '@/store'
import { getToken } from '@/utils/auth'
export default {
  data() {
    return {
      visible: false,
      demandId: -1,
      // 上传控件使用
      uploadParams: {},
      fileList: []
    }
  },
  methods: {
    init(id) {
      this.visible = true
      this.demandId = id
    },
    // upload的一些方法
    handlePreview(file) {
      console.log(file)
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    resourceUploadSuccess(response) {
      this.$message.success(response.message)
    },
    resourceUploadError(response) {
      this.$message.error(response)
    },
    myUpload(param) {
      const formData = new FormData()
      formData.append('file', param.file)
      const url = '/autotest/case/upload?uploadId=666666&demandId=' + this.demandId
      // 参考这个实现：https://www.cnblogs.com/yulj/p/8494465.html
      if (store.getters.token) {
        axios({
          baseURL: process.env.VUE_APP_BASE_API,
          method: 'post',
          url: url,
          data: formData,
          responseType: 'blob',
          headers: { 'token': getToken() }
        }).then(response => {
          console.info(response)
          this.download(response.data)
          this.visible = false
          this.$emit('reflushDataList')
        }).catch((error) => {
          console.error(error)
        })
      } else {
        this.$message.error('请登录后操作')
      }
    },
    // 下载文件
    download(data) {
      if (!data) {
        return
      }
      const url = window.URL.createObjectURL(new Blob([data]))
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      link.setAttribute('download', '用例上传结果.xlsx')

      document.body.appendChild(link)
      link.click()
    }
  }
}
</script>

<style>
</style>
